define(function(require, exports, module) {

  var Backbone = require('backbone');
  var $ = require('jquery');
  var _ = require('underscore');
  var jsonview = require('jsonview');

  var d3 = require('d3')

  function main() {
    var $app = $('<div id="app">').height(300)
    $('#main').html($app);

    var option = {
      series: [{
        id: 'ld.server1',
        value: 123
      },{
        id: 'ld.server3',
        value: 34
      },{
        id: 'ld.server2',
        value: 35
      },{
        id: 'ld.server4',
        value: 32
      }]
    }
    new ldj(option, $app)
  }

  function ldj(option, el, theme, props) {
    this.$el = $(el)
    this.$container = $('<svg width="100%" height="100%" text-anchor="middle"/>')
    this.$el.html('').append(this.$container)

    this.svg = d3.select(this.$container[0])
    this.width = this.$el.width()
    this.height = this.$el.height()

    this.pack = d3.pack()
        .size([this.width, this.height])
        // .radius(function(d) {
        //   return 30 + d.value * ( width / (30 * 12) * 0.001);
        // })
        .padding(5.5);
    this.setData(option)
  }

  ldj.prototype.setData = function(partialOption) {
    if (partialOption && partialOption.series) {
      let _series = _.clone(partialOption.series, true)
      //value需要转换为number
      _series.map(item => {
        item.value = +item.value
      })
      _series.columns = ['id', 'value']

      console.log(_series)

      let root = d3.hierarchy({
        children: _series
      }).sum(data => {
        return data.value;
      })
      .each(d => {
        console.log(d)
        if (id = d.data.id) {
          var id, i = id.lastIndexOf(".");
          d.id = id;
          d.package = id.slice(0, i);
          d.class = id.slice(i + 1);
        }
      })

      let node = this.svg.selectAll('.node')
        .data(this.pack(root).leaves())
        .enter().append('circle')

      node.attr('class', 'node')
      .attr('transform', function(d) {
        return 'translate(' + d.x + ',' + d.y + ')';
      })
      .attr('r', function(d) {
        return d.r
      });

    }
  }

  return main;
})